package exercise;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？
 * 请你找出所有和为 0 且不重复的三元组。
 */
public class exercise04 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        if(nums[0] > 0 || nums.length < 3){
            return null;
        }
        // 存放每个序列
        List<Integer> list = new ArrayList<>();

        int first = 0;
        int last = nums.length-1;
        for (int i = 0; i < nums.length; i++) {
            first = i+1;
            last = nums.length-1;
            for (;first < last;) {
                if(nums[first] + nums[last] == -nums[i]){
                    list.add(nums[i]);
                    list.add(nums[first]);
                    list.add(nums[last]);
                }else if(nums[first] + nums[last] < -nums[i]){
                    first++;
                }else if(nums[first] + nums[last] > -nums[i]){
                    last--;
                }
            }
            if(list.size() > 0){
                lists.add(list);
                list.clear();
            }
        }
        return lists;
    }

    public static void main(String[] args) {

        exercise04 exercise04 = new exercise04();
        int[] nums = {-1,0,1,2,-1,-4};
        System.out.println(exercise04.threeSum(nums));
    }
}
